package by.parfen.game.filters;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import by.parfen.game.datamodel.etc.SessionObject;
import by.parfen.game.datamodel.etc.SessionsData;

@WebFilter(filterName = "LogFilter", urlPatterns = { "/log" })
public class LogFilter implements Filter {

	private SessionsData sessionData;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;

		// Get the IP address of client machine.
		String sessionId = request.getSession().getId();

		// as example of storing some session data (session id)
		sessionData.addSessionId(sessionId);
		System.out.println("List of sessions id:");
		for (SessionObject sessionObject : sessionData.sessionDataList()) {
			System.out.println(sessionObject.getSessionId());
		}

		// Log the IP address and current timestamp.
		System.out.println("Session: " + sessionId + ", Time " + new Date().toString());

		List<String> users = (List<String>) request.getSession().getAttribute("users");
		for (int i = 0; null != users && i < users.size(); i++) {
			if (i == 0) {
				System.out.println("Sessions users list");
			}
			System.out.println(users.get(i));
			// LOGGER.info(users.get(i));
		}
		String lastUser = (String) request.getSession().getAttribute("lastUser");
		if (lastUser != null) {
			System.out.println("Last user: " + lastUser);
		}
		System.out.println();

		chain.doFilter(req, res);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		// Get init parameter
		String testParam = config.getInitParameter("test-param");

		// Print the init parameter
		System.out.println("Test Param: " + testParam);

		sessionData = new SessionsData();

	}

}
